package com.zhinong.aop;

import com.zhinong.annotation.DeleteCache;
import com.zhinong.annotation.SelectCache;
import com.zhinong.result.PageResult;
import com.zhinong.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
public class DeleteCacheAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.zhinong.annotation.DeleteCache)")
    public void deletePointCut(){}

    @After("deletePointCut()")
    public Result deleteCache(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        DeleteCache annotation = methodSignature.getMethod().getAnnotation(DeleteCache.class);
        String deleteKey = annotation.name()+"*";
        PageResult pageResult = (PageResult) redisTemplate.opsForValue().get(deleteKey);
        redisTemplate.delete(pageResult);
        return Result.success();
    }
}
